'use strict';

const {
	Controller
} = require('egg');
const fs = require("fs")
const path = require("path")

class GoodsController extends Controller {

	async setcomments() {
		let userid=this.ctx.session.id
		if(!userid){
			this.ctx.body={code:4004,info:"登录失效,重新登录"}
			return 
		}
		let goodsid=this.ctx.request.query.id
		let content1=this.ctx.request.query.content1
		let sql=`insert into comments (userid,goodsid,content1) values (${userid},${goodsid},"${content1}")`
		this.ctx.app.mysql.query(sql)
		this.ctx.body={code:2006,info:"评论成功"}
	}
	async getcomments() {
		let {
			id
		} = this.ctx.request.query
		let sql =
			`SELECT userimg,nickname,content1,userid from user inner join comments on comments.userid=user.id WHERE comments.goodsid=${id}`
		let arr = await this.ctx.app.mysql.query(sql)
		this.ctx.body = arr
	}
	async goodsdetail() {
		let {
			id
		} = this.ctx.request.query
		let sql = `select * from goods where id=${id}`
		let arr = await this.ctx.app.mysql.query(sql)
		this.ctx.body = arr
	}
	async getgoods() {
		let {
			keyword,
			start
		} = this.ctx.request.query
		let sql = `select * from goods where title like "%${keyword}%"  limit ${start},10`
		let arr = await this.ctx.app.mysql.query(sql)
		this.ctx.body = arr
	}
	async addgoods() {
		const {
			ctx
		} = this;
		let files = this.ctx.request.files
		let {
			title,
			price,
			img
		} = this.ctx.request.body
		let oldpath = files[0].filepath
		let imgname = path.basename(oldpath)
		let newpath = __dirname + "/../public/server/goodsimg/" + imgname
		fs.copyFileSync(oldpath, newpath)
		img = "/server/goodsimg/" + imgname
		let sql = `insert into goods (title,price,img) values ("${title}","${price}","${img}")`
		await this.ctx.app.mysql.query(sql)
		ctx.body = {
			code: 26,
			info: "添加商品成功"
		};
	}
}

module.exports = GoodsController;